<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title=" 注意：只允许为第三级分类设置参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="catemodel"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 标签页 -->

      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            @click="manyDialog"
            size="mini"
            type="primary"
            :disabled="btnDisabled"
            >添加参数</el-button
          >
          <!-- 动态参数的表格-->

          <el-table :data="manyTableList" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleCloseDi(i, scope.row)"
                >
                  {{ item }}</el-tag
                >
                <!-- new Tag -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>

            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="editDialog(scope.row.attr_id)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                >
                  编辑</el-button
                >
                <el-button size="mini" type="danger" icon="el-icon-delete">
                  删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button
            @click="onlyDialog"
            size="mini"
            type="primary"
            :disabled="btnDisabled"
            >添加属性</el-button
          >
          <!-- 静态属性的表格-->

          <el-table :data="onlyTableList" border stripe style="width: 100%">
            <!-- 静态属性的展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleCloseDi(i, scope.row)"
                >
                  {{ item }}</el-tag
                >
                <!-- new Tag -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>

            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="editDialog(scope.row.attr_id)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                >
                  编辑</el-button
                >
                <el-button size="mini" type="danger" icon="el-icon-delete">
                  删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      @close="addDialogClosed"
      :title="'添加' + TextTitle"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="TextTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      @close="editDialogClosed"
      :title="'修改' + TextTitle"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="TextTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'VueShopParams',



  data() {
    return {
      //商品分类列表
      cateList: [],
      //级联选择框的配置信息
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'

      },
      //   级联选择框的默认绑定值
      catemodel: [],
      activeName: 'many',
      // 动态参数的数据
      manyTableList: [],
      // 静态属性的数据
      onlyTableList: [],
      // 添加对话框的显示与隐藏
      addDialogVisible: false,
      // 添加对话框的显示与隐藏
      editDialogVisible: false,
      //  添加参数的表单对象
      addForm: {
        attr_name: ''
      },
      editForm: {

      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },


    }
  },
  created() {
    this.getCateList()
  }
  ,

  mounted() {


  },
  computed: {
    //如果被禁用返回ture
    btnDisabled() {
      return this.catemodel.length !== 3 ? true : false
    },
    //当前选中的三级分类id
    cateId() {
      return this.catemodel.length === 3 ? this.catemodel[2] : null
    },
    // 返回标题
    TextTitle() {
      return this.activeName === "many" ? '动态参数' : '静态属性'
    }
  },

  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) return this.$message({ showClose: true, message: res.meta.message, type: 'error' })
      this.cateList = res.data
      // console.log(this.cateList);
    },

    // 获取参数的列表数据
    async getParamsData() {

      // 选择的不是三级分类
      if (this.catemodel.length !== 3) {
        this.catemodel = [],
          this.onlyTableList = [],
          this.manyTableList = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''

      })
      // 给每个item设置一个inputValue

      // console.log(res.data);

      // console.log(res);
      if (this.activeName === "many") {
        this.manyTableList = res.data
      } else {
        this.onlyTableList = res.data

      }



    },

    //   监听选择商品分类的级联选择框的改变
    handleChange() {

      this.getParamsData()


    },
    // 标签点击函数
    handleTabsClick() {
      this.getParamsData()

      // console.log(this.activeName);
    },
    // 添加动态参数
    manyDialog() {

      this.addDialogVisible = true
    },
    // 添加静态属性
    onlyDialog() {

      this.addDialogVisible = true
    },
    // 修改静态属性

    async editDialog(attr_id) {
      // console.log(attr_id)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })

      this.editForm = res.data
      this.editDialogVisible = true

    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加参数
    addParams() {
      this.$refs['addFormRef'].validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })


        this.getParamsData()
        this.$message({ showClose: true, message: res.meta.msg, type: 'success' })
        this.addDialogVisible = false

      })
    },
    editParams() {
      this.$refs['editFormRef'].validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })
        this.$message({ showClose: true, message: res.meta.msg, type: 'success' })
        this.getParamsData()
        this.editDialogVisible = false




      })
    },
    // 监听点击输入框
    showInput(scope) {
      scope.inputVisible = true
      // 页面被重新渲染之后 调用nextTick
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 键盘抬起和失去焦点
    handleInputConfirm(row) {
      if (row.inputValue.length === 0) {
        row.inputValue = ""
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ""
      row.inputVisible = false
      this.setTagValue(row)



    },

    //  修改tag的值
    async setTagValue(row) {
      // 发送网络请求 保存数据
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')

      })
      // console.log(res);

      if (res.meta.status !== 200) return this.$message({ showClose: true, message: res.meta.msg, type: 'error' })
      this.$message({ showClose: true, message: res.meta.msg, type: 'success' })
      // row.inputVisible = false
    },


    // 关闭tag 删除节点
    handleCloseDi(i, row) {
      // 删除当前attr_vals对应的索引
      row.attr_vals.splice(i, 1)
      console.log(row.attr_vals);

      this.setTagValue(row)

    }






  }

};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-table {
  margin-top: 15px;
}
.input-new-tag {
  width: 120px;
}
.el-tag {
  margin: 0 15px;
}
</style>